package com.qipay.sp.excutor.shanhongyun;

import com.qipay.baas.model.Order;
import com.qipay.scalar.type.ApiTypeEnum;
import com.qipay.sp.excutor.AbstractExcutor;
import com.qipay.utils.SignSortMD5Utils;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class ShyunWxWapPayExcutor extends AbstractExcutor {

    private final static String KEY_NAME="key";
    private final static String CONFIG_KEY_NAME="key";
    private final static String CONFIG_APPID_NAME="app_id";
    private final static String SIGN_NAME="sign";

    private final static String API_PARAM_VERSION="version";
    private final static String API_PARAM_APP_ID="app_id";
    private final static String API_PARAM_OUT_TRADE_NO="order_id";
    private final static String API_PARAM_BODY="body";
    private final static String API_PARAM_TOTAL_AMOUNT="amount";

    private final static String API_URL="https://api.shanhongyun.com/payment/pay";

    @Override
    protected ApiTypeEnum getApiTypeEnum() {
        return ApiTypeEnum.WX_WAP_PAY;
    }

    @Override
    protected Map<String, Object> getApiParams(Order order, Map<String, Object> spconfig, Map<String, Object> extendOrderParams) {
        Map<String, Object> apiParams = new HashMap<>();
        apiParams.put(API_PARAM_OUT_TRADE_NO, order.getTradeNo());
//        apiParams.put(API_PARAM_BODY, order.getBody());
        apiParams.put(API_PARAM_TOTAL_AMOUNT, order.getAmount());

        return apiParams;
    }

    @Override
    protected Map<String, Object> run(Map<String, Object> spconfig, Map<String, Object> params) throws Exception {

        Object key = getVal(spconfig, CONFIG_KEY_NAME);
        Object appId = getVal(spconfig, CONFIG_APPID_NAME);

        params.put(API_PARAM_VERSION, "1.0");
        params.put(API_PARAM_APP_ID, appId);


        String sign = SignSortMD5Utils.getSign(params,
                key.toString(),
                ShyunWxWapPayExcutor.SIGN_NAME,
                ShyunWxWapPayExcutor.KEY_NAME);

        params.put(ShyunWxWapPayExcutor.SIGN_NAME, sign);

        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        sb.deleteCharAt(sb.length()-1);

        String redirectUrl = API_URL + "?" + sb.toString();

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("result_code", "0");
        resultMap.put("pay_info", redirectUrl);
        return resultMap;
    }
}
